class HttpResponseHandler {
  constructor (data = {}) {
    this.config = data.config
    this.handleHttpError = data.handleHttpError || (() => {})
    this.handleBusinessOk = data.handleBusinessOk || (() => {})
    this.handleBusinessError = data.handleBusinessError || (() => {})
  }

  async handle (httpResponse) {
    // 若http请求出错
    const httpCode = httpResponse.getCode()
    if (httpCode != 200) {
      const msg = httpResponse.getMessage()
      this.handleHttpError({ message: msg })
      return Promise.reject(msg)
    }
    // 若http请求成功，且得到成功业务码
    const businessCode = httpResponse.getBusinessCode()
    if (businessCode == this.config.businessOkCode) {
      return httpResponse.getData()
    }
    // 得到报错的业务码，大部分错误走统一错误处理，部分走自定义处理
    if (this.config.businessErrorCodeEscape.indexOf(businessCode) !== -1) {
      return {
        waitHandle: true,
        code: businessCode,
        data: httpResponse.getData(),
        message: httpResponse.getBusinessMessage()
      }
    } else {
      const msg = httpResponse.getBusinessMessage()
      this.handleBusinessError({ message: msg })
      return Promise.reject(msg)
    }
  }
}

export default HttpResponseHandler